package com.crocodileQ.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crocodileQ.common.AppException;
import com.crocodileQ.common.R;
import com.crocodileQ.domain.VO.UserInfoVO;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.mapper.UserMapper;
import com.crocodileQ.service.UserService;
import com.crocodileQ.utils.BeanCopyUtil;
import com.crocodileQ.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-03 09:59:05
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户信息查询
     * @return
     */
    public R userInfo() {
        //查询用户id
        Long userId = SecurityUtils.getUserId();

        //查询用户信息
        User user = getById(userId);
        //封装成userInfo
        UserInfoVO userInfoVO = BeanCopyUtil.copyBean(user, UserInfoVO.class);

        return R.success(userInfoVO);
    }

    /**
     * 更新用户信息查询
     * @return
     */
    public R<String> updateUserInfo(User user) {
       //条件判断user的password和username为空才能更改
//        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(User::getId,user.getId());
//        updateWrapper.set(user.getPassword()==null,User::getPassword,user.getPassword());

        //查询提交的用户信息id,是否和token中的信息一致
        Long userId = SecurityUtils.getUserId();
        if(!userId.equals(user.getId())){
            throw new AppException(AppExceptionMsgEnum.ONLY_UPDATE_SELF);
        }

        updateById(user);
        return R.success("修改成功");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    public R<String> register(User user) {
        //数据合法性校验 spring validation 框架


        //数据是否重复
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        if(count(queryWrapper)>0){
            throw new AppException(AppExceptionMsgEnum.USERNAME_EXIST);
        }

//        密码加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //保存用户信息
        save(user);

        return R.success("操作成功");
    }
}

